//
//  ChangeGoodsAddressViewController.m
//  1gene
//
//  Created by 1jiyin on 16/5/6.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "ChangeGoodsAddressViewController.h"
#import "GoodsAddressDetailViewController.h"

@interface ChangeGoodsAddressViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,copy)NSMutableArray *dataArray;

@property(nonatomic,copy)UITableView *myTableView;

@property(nonatomic,assign)NSInteger deleteCellIndex;

@property(nonatomic,copy)UIView *myView;

@property(nonatomic,copy)UIView *navigationBarView;

@property(nonatomic,copy)NSString *addressId;

@end

@implementation ChangeGoodsAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.view addSubview:[UIView new]];
    [self createNavigation];
    [self createUI];
    [self getAddressData];
    // Do any additional setup after loading the view.
}

-(void)createUI
{
    UITableView *table=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-40-64) style:UITableViewStylePlain];
    table.delegate=self;
    table.dataSource=self;
    table.tableHeaderView=[UIView new];
    table.tableFooterView=[UIView new];
    [self.view addSubview:table];
    table.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getAddressData];
    }];
    table.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _myTableView=table;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1; //seconds  设置响应时间
    [table addGestureRecognizer:lpgr]; //启用长按事件

    
    
    
    
    
    UIButton *addAddress=[UIButton buttonWithType:UIButtonTypeCustom];
    addAddress.frame=CGRectMake(0, CGRectGetMaxY(table.frame), self.view.frame.size.width, 40);
    addAddress.backgroundColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    addAddress.titleLabel.font=[UIFont systemFontOfSize:16];
    [addAddress setTitle:@"添加收货地址" forState:UIControlStateNormal];
    [addAddress setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addAddress addTarget:self action:@selector(addAddressBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addAddress];
    
    
    [self createMyView];
}

-(void)createMyView
{
    _myView=[[UIView alloc]initWithFrame:self.view.bounds];
    _myView.hidden=YES;
    [self.view addSubview:_myView];
    
    UIView *backgroundView=[[UIView alloc]initWithFrame:_myView.bounds];
    backgroundView.alpha=0.5;
    backgroundView.backgroundColor=[UIColor grayColor];
    [_myView addSubview:backgroundView];
    
    UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame=_myView.bounds;
    [btn1 addTarget:self action:@selector(btn1Click:) forControlEvents:UIControlEventTouchUpInside];
    [_myView addSubview:btn1];
    
    UIView *v1=[[UIView alloc]init];
    v1.backgroundColor=[UIColor whiteColor];
    v1.layer.borderColor=[UIColor whiteColor].CGColor;
    v1.layer.borderWidth=2.0;
    v1.layer.cornerRadius=5.0;
    v1.bounds=CGRectMake(0, 0, 200, 100);
    v1.center=self.view.center;
    [_myView addSubview:v1];
    
    UILabel *l1=[[UILabel alloc]initWithFrame:CGRectMake(0, 15, v1.frame.size.width, 30)];
    l1.text=@"确定删除吗";
    l1.textColor=[UIColor blackColor];
    l1.font=[UIFont systemFontOfSize:16];
    l1.textAlignment=NSTextAlignmentCenter;
    [v1 addSubview:l1];
    
    
    UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame=CGRectMake(0, v1.frame.size.height-30, (v1.frame.size.width-0.5)/2.0, 30);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTitleColor:[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1] forState:UIControlStateNormal];
    [v1 addSubview:cancelBtn];
    
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(cancelBtn.frame), cancelBtn.frame.origin.y, 0.5, 30)];
    line.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [v1 addSubview:line];
    
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(CGRectGetMaxX(line.frame), v1.frame.size.height-30, (v1.frame.size.width-0.5)/2.0, 30);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn setTitleColor:[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1] forState:UIControlStateNormal];
    [v1 addSubview:sureBtn];
    
    
}

//取消
-(void)cancelBtnClick:(UIButton *)sender
{
    _myView.hidden=YES;
    _navigationBarView.hidden=YES;
}
//确定
-(void)sureBtnClick:(UIButton *)sender
{
    _myView.hidden=YES;
    _navigationBarView.hidden=YES;
    AddressModel *model=_dataArray[_deleteCellIndex];
    _addressId=model.addressId;
    
    [_dataArray removeObjectAtIndex:_deleteCellIndex];
    [_myTableView reloadData];
    
    [self deleteAddress];
    
}
//背景
-(void)btn1Click:(UIButton *)sender
{
    _myView.hidden=YES;
    _navigationBarView.hidden=YES;
}



-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer  //长按响应函数
{
    CGPoint p = [gestureRecognizer locationInView:_myTableView];
    
    
    NSIndexPath *indexPath = [_myTableView indexPathForRowAtPoint:p];//获取响应的长按的indexpath
    if (indexPath == nil) {
        return;
    }else{
        NSLog(@"点击了哪一个cell======%ld",indexPath.row);
        _deleteCellIndex=indexPath.row;
        
        //_navigationBarView.alpha=0;
        //_myView.alpha=0;
        //[UIView animateWithDuration:0.6 animations:^{
            _navigationBarView.hidden=NO;
            _myView.hidden=NO;
          //  _navigationBarView.alpha=1;
           // _myView.alpha=1;
        //}];
    }
    
}



-(void)addAddressBtnClick:(UIButton *)sender
{
    GoodsAddressDetailViewController *vc=[GoodsAddressDetailViewController new];
    vc.modelState=1;
    [self.navigationController pushViewController:vc animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    cell.backgroundColor=[UIColor whiteColor];
    AddressModel *model=_dataArray[indexPath.row];
    UILabel *l1=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, (self.view.frame.size.width-70)/2.0, 30)];
    l1.text=[NSString stringWithFormat:@"收货人:%@",model.receiver];
    l1.textColor=[UIColor blackColor];
    l1.font=[UIFont systemFontOfSize:14];
    [cell.contentView addSubview:l1];
    
    
    UILabel *l2=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l1.frame), 10, (self.view.frame.size.width-70)/2.0, 30)];
    l2.text=[NSString stringWithFormat:@"手机号:%@",model.phone];
    l2.textColor=[UIColor blackColor];
    l2.font=[UIFont systemFontOfSize:14];
    [cell.contentView addSubview:l2];
    
    
    UILabel *l3=[[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(l1.frame), self.view.frame.size.width-15-55, 30)];
    l3.text=[NSString stringWithFormat:@"收货地址:%@%@%@",model.province,model.city,model.detail];
    l3.textColor=[UIColor blackColor];
    l3.font=[UIFont systemFontOfSize:14];
    l3.numberOfLines=0;
    if ([l3 boundingRectWithSize:CGSizeMake(l3.frame.size.width, 0)].height>30) {
        l3.frame=CGRectMake(15, CGRectGetMaxY(l1.frame), self.view.frame.size.width-15-55, 50);
    }
    [cell.contentView addSubview:l3];
    
    
    UIButton *changeMessageBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    changeMessageBtn.tag=indexPath.row;
    changeMessageBtn.frame=CGRectMake(self.view.frame.size.width-15-25, (60-25)/2.0+10, 25, 25);
    [changeMessageBtn setBackgroundImage:[UIImage imageNamed:@"app_right"] forState:UIControlStateNormal];
    [changeMessageBtn addTarget:self action:@selector(changeMessageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:changeMessageBtn];
    
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 15)];
    line1.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [cell.contentView addSubview:line1];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressModel *model=_dataArray[indexPath.row];
    self.returnAddressModel(model);
    [self.navigationController popViewControllerAnimated:YES];
}



//修改基本信息
-(void)changeMessageBtnClick:(UIButton *)sender
{
    GoodsAddressDetailViewController *vc=[GoodsAddressDetailViewController new];
    vc.model=(id)_dataArray[sender.tag];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)createNavigation
{
    self.navigationController.navigationBar.hidden=NO;
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"地址管理";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
    
    _navigationBarView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    _navigationBarView.hidden=YES;
    UIView *myCustomBackgroundView=[[UIView alloc]initWithFrame:_navigationBarView.bounds];
    myCustomBackgroundView.backgroundColor=[UIColor grayColor];
    myCustomBackgroundView.alpha=0.6;
    [_navigationBarView addSubview:myCustomBackgroundView];
    
    UIButton *btn11=[UIButton buttonWithType:UIButtonTypeCustom];
    btn11.frame=_navigationBarView.bounds;
    [btn11 addTarget:self action:@selector(navigationBarViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_navigationBarView addSubview:btn11];
    
    
    
    
    [self.navigationController.view addSubview:_navigationBarView];
}


-(void)navigationBarViewBtnClick:(UIButton *)sender
{
    _myView.hidden=YES;
    _navigationBarView.hidden=YES;
}

#pragma mark 返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//收货地址
-(void)getAddressData
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [self.view showCicle:YES];
    
    [manager GET:[NSString stringWithFormat:AllAddress,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [_myTableView.header endRefreshing];
         [self.view showCicle:NO];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        _dataArray=[NSMutableArray array];
        if (dic) {
            for (NSDictionary *dic1 in dic[@"addresss"]) {
                AddressModel *model=[[AddressModel alloc]initWithDictionary:dic1];
                [_dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [_myTableView reloadData];
            });
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_myTableView.header endRefreshing];
         [self.view showCicle:NO];
        NSLog(@"error%@",error.localizedDescription);
    }];
}

//删除收货地址
-(void)deleteAddress
{
    
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    
    [manager DELETE:[NSString stringWithFormat:DeleteAddress,token,_addressId] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"删除收货地址%@",dic);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];

}

-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setTranslucent:NO];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar setTranslucent:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
